package com.anysoft.user;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anysoft.MentorConst;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.adapter.UserManageListviewAdapter;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.LoginOutBean;
import com.anysoft.bean.UserBean;
import com.anysoft.login.LoginActivity;
import com.anysoft.login.UserIconLoginActivity;
import com.anysoft.utils.AnalyticsEventUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.view.dialog.DialogUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wwq on 2017/1/20.
 * 用户切换列表,可滑动删除条目
 */

public class UserManageListviewActivity extends BaseActivity {

    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightButton)
    Button rightButton;
    @BindView(R.id.titlebar)
    FrameLayout titlebar;
    @BindView(R.id.sml_user_manage)
    SwipeMenuListView smlUserManage;

    private ArrayList<UserBean> userBeanList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_user_manage_listview);
        ButterKnife.bind(this);

        title.setText("用户切换");
        List<UserBean> listUser = findUserList();
        if (listUser != null) {
            for (UserBean bean : listUser) {
                if ("1".equals(bean.getRecordIdentNumber())) {
                    userBeanList.add(bean);
                }
            }
        }
//        userBeanList.addAll(findUserList());

        initViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    protected View footView;

    private void initViews() {

        footView = View.inflate(this, R.layout.recyclerview_item_user_manage_add, null);
        footView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent().setClass(mActivity, LoginActivity.class));
                finish();
            }
        });
        LinearLayout footerParent = new LinearLayout(this);
        footerParent.addView(footView);
        smlUserManage.addFooterView(footerParent);
        footView.setVisibility(View.VISIBLE);

        final UserManageListviewAdapter adapter = new UserManageListviewAdapter(this, userBeanList);

        smlUserManage.setAdapter(adapter);

        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(202, 207,
                        224)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("删除");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);
            }
        };

        // set creator
        smlUserManage.setMenuCreator(creator);

        // step 2. listener item click event
        smlUserManage.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                final UserBean userBean = userBeanList.get(position);
                switch (index) {
                    case 0:
                        if (mentorApplication.userBean != null && mentorApplication.userBean.getUserId().equals(userBean.getUserId())) {
                            showToast("当前登录账户不能删除");
                            return true;
                        }

                        DialogUtils utils = new DialogUtils();
                        utils.contentAlert(mActivity, "是否删除账户", "删除当前账户，将清除账户在手机上所有资料信息。", "删除", "取消");
                        utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                            @Override
                            public void OnContentDialogSbtnClick() {
                                if (PreferencesUtils.getString(UserManageListviewActivity.this, MentorConst.LAST_LOGIN_USER_ID, "").equals(userBean.getUserId())) {
                                    PreferencesUtils.putString(UserManageListviewActivity.this, MentorConst
                                            .LAST_LOGIN_USER_ID, "");
                                }
                                if (deleteUser(userBean.getUserId())) {
                                    clearSecretKey(mActivity);
                                    userBeanList.remove(position);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        });
                        break;
                    case 1:
                        break;
                }
                return false;
            }
        });

        // set SwipeListener
        smlUserManage.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });

        // set MenuStateChangeListener
        smlUserManage.setOnMenuStateChangeListener(new SwipeMenuListView.OnMenuStateChangeListener() {
            @Override
            public void onMenuOpen(int position) {
            }

            @Override
            public void onMenuClose(int position) {
            }
        });

        smlUserManage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                UserBean userBean = userBeanList.get(position);
                if (mentorApplication.userBean != null && mentorApplication.userBean.getUserId().equals(userBean.getUserId())) {
                    showToast("该账户已登录");
                    return;
                }
//                showToast("-----" + userBeanList.get(position).getUserId() + "-----");

                if (mentorApplication.userBean != null) {
                    DialogUtils utils = new DialogUtils();
                    utils.contentAlert(mActivity, "提示", "确定要退出当前账户", "确定", "取消");
                    utils.setOnContentDialogSbtnListener(new DialogUtils.OnContentDialogSbtnListener() {
                        @Override
                        public void OnContentDialogSbtnClick() {
                            loginOut(userBeanList.get(position));
                        }
                    });
                } else {
                    Intent intent = new Intent().setClass(mActivity, UserIconLoginActivity.class);
                    intent.putExtra("userId", userBeanList.get(position).getUserId());
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    public void loginOut(final UserBean userBean) {
        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());
        OkGo.<String>post(HostConstant.LOGIN_OUT)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateLoginOut(response.body(), userBean);
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateLoginOut(String json, UserBean userBean) {

        LoginOutBean bean;

        try {
            bean = new Gson().fromJson(json, LoginOutBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        mentorApplication.signOut();
        AnalyticsEventUtils.toLogoutEvent(this);
        Intent intent = new Intent().setClass(mActivity, UserIconLoginActivity.class);
        intent.putExtra("userId", userBean.getUserId());
        startActivity(intent);
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @OnClick({R.id.leftButton, R.id.rightButton})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftButton:
                finish();
                break;
            case R.id.rightButton:
                break;
        }
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }
}
